<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>网店店铺管理系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
  
  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36CFC9',
            success: '#52C41A',
            warning: '#FAAD14',
            danger: '#FF4D4F',
            gray: {
              100: '#F5F5F5',
              200: '#E5E5E5',
              300: '#D9D9D9',
              400: '#BFBFBF',
              500: '#8C8C8C',
              600: '#595959',
              700: '#434343',
              800: '#262626',
              900: '#1F1F1F',
            }
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .table-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .transition-custom {
        transition: all 0.3s ease;
      }
      .scrollbar-hide::-webkit-scrollbar {
        display: none;
      }
      .status-badge {
        @apply px-2 py-1 rounded-full text-xs font-medium;
      }
      .sortable {
        @apply cursor-pointer;
      }
      .sort-icon {
        @apply ml-1 text-gray-400;
      }
    }
  </style>
</head>
<body class="bg-gray-100 min-h-screen font-sans">
  <!-- 顶部导航 -->
  <header class="bg-white shadow-sm shadow sticky top-0 z-50 transition-custom">
    <div class="container mx-auto px-4 py-4 flex flex-col md:flex-row justify-between items-center">
      <div class="flex items-center mb-4 md:mb-0">
        <i class="fa fa-shopping-bag text-primary text-2xl mr-3"></i>
        <h1 class="text-[clamp(1.25rem,3vw,1.75rem)] font-bold text-gray-800">网店店店铺管理系统</h1>
      </div>
      
      <div class="flex space-x-3">
        <button id="addRowBtn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg flex items-center transition-custom shadow-md hover:shadow-lg">
          <i class="fa fa-plus mr-2"></i>添加记录
        </button>
        <div class="relative group">
          <button class="bg-gray-800 hover:bg-gray-700 text-white px-4 py-2 rounded-lg flex items items-center transition-custom shadow-md hover:shadow-lg">
            <i class="fa fa-download mr-2"></i>导出
            <i class="fa fa-caret-down ml-2"></i>
          </button>
          <div class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg overflow-hidden z-10 hidden group-hover:block transition-custom">
            <button id="exportXLSX" class="w-full text-left px-4 py-2 hover:bg-gray-100 transition-custom items-center">
              <i class="fa fa-file-excel-o text-success mr-2"></i>导出为XLSX
            </button>
            <button id="exportWPS" class="w-full text-left px-4 py-2 hover:bg-gray-100 transition-custom flex items-center">
              <i class="fa fa-file-text-o text-primary mr-2"></i>导出为WPS
            </button>
          </div>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="container mx-auto px-4 py-8">
    <!-- 数据概概览卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div class="bg-white-white rounded-xl p-6 shadow-sm hover:shadow-md transition-custom border-l-4 border-primary">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-gray-500 text-sm mb-1">总店铺数</p>
            <h3 class="text-2xl font-bold text-gray-800" id="totalShops">0</h3>
          </div>
          <div class="bg-primary/10 p-3 rounded-lg">
            <i class="fa fa-store text-primary"></i>
          </div>
        </div>
        <div class="mt-4 text-sm">
          <span class="text-success"><i class="fa fa-arrow-up"></i> 0%</span>
          <span class="text-gray-500 ml-2">较上月</span>
        </div>
      </div>
      
      <div class="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-custom border-l-4 border-secondary">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-gray-500 text-sm mb-1">在用手机号</p>
            <h3 class="text-2xl font-bold text-gray-800" id="usedPhones">0</h3>
          </div>
          <div class="bg-secondary/10 p-3 rounded-lg">
            <i class="fa fa-mobile text-secondary text-xl"></i>
          </div>
        </div>
        <div class="mt-4 text-sm">
          <span class="text-success"><i class="fa fa-arrow-up"></i> 0%</span>
          <span class="text-gray-500 ml-2">较上月</span>
        </div>
      </div>
      
      <div class="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-custom border-l-4 border-warning">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-gray-500 text-sm mb-1">待处理退店</p>
            <h3 class="text-2xl font-bold text-gray-800" id="pendingClose">0</h3>
          </div>
          <div class="bg-warning/10 p-3 rounded-lg">
            <i class="fa fa-hourglass-half text-warning"></i>
          </div>
        </div>
        <div class="mt-4 text-sm">
          <span class="text-danger"><i class="fa fa-arrow-up"></i> 0%</span>
          <span class="text-gray-500 ml-2">较上月</span>
        </div>
      </div>
      
      <div class="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-custom border-l-4 border-success">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-gray-500 text-sm mb-1">可复用资源</p>
            <h3 class="text-2xl font-bold text-gray-800" id="reusableResources">0</h3>
          </div>
          <div class="bg-success/10 p-3 rounded-lg">
            <i class="fa fa-refresh text-success"></i>
          </div>
        </div>
        <div class="mt-4 text-sm">
          <span class="text-success"><i class="fa fa-arrow-up"></i> 0%</span>
          <span class="text-gray-500 ml-2">较上月</span>
        </div>
      </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="bg-white rounded-xl p-6 mb-8 shadow-sm">
      <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">人员</label>
          <input type="text" id="filterPerson" placeholder="搜索人员..." class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">手机号</label>
          <input type="text" id="filterPhone" placeholder="搜索手机号后四位..." class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">店铺状态</label>
          <select id="filterStatus" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
            <option value="">全部状态</option>
            <option value="运营中">运营中</option>
            <option value="退店处理中">退店处理中</option>
            <option value="已关闭">已关闭</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">退店类型</label>
          <select id="filterCloseType" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
            <option value="">全部类型</option>
            <option value="有待付款">有待付款</option>
            <option value="无待付款">无待付款</option>
            <option value="有公示期">有公示期</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">押金状态</label>
          <select id="filterDepositStatus" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
            <option value="">全部状态</option>
            <option value="未到账">未到账</option>
            <option value="已到账">已到账</option>
          </select>
        </div>
      </div>
      <div class="mt-4 flex justify-end">
        <button id="resetFilter" class="text-gray-600 hover:text-gray-800 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-custom">
          <i class="fa fa-refresh mr-1"></i>重置筛选
        </button>
      </div>
    </div>
    
    <!-- 新增：可复用查询区域 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
      <div class="bg-white rounded-xl p-6 shadow-sm">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold text-gray-800">可复用手机号查询</h3>
          <button id="checkReusablePhones" class="bg-primary hover:bg-primary/90 text-white px-3 py-1 rounded-lg text-sm transition-custom">
            <i class="fa fa-search mr-1"></i>查询
          </button>
        </div>
        <div id="reusablePhonesResult" class="mt-2 p-4 bg-gray-50 rounded-lg min-h-[100px]">
          <p class="text-gray-500 text-sm">点击查询按钮查看可复用的手机号尾号</p>
        </div>
      </div>
      
      <div class="bg-white rounded-xl p-6 shadow-sm">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold text-gray-800">可复用人员查询</h3>
          <button id="checkReusablePersons" class="bg-primary hover:bg-primary/90 text-white px-3 py-1 rounded-lg text-sm transition-custom">
            <i class="fa fa-search mr-1"></i>查询
          </button>
        </div>
        <div id="reusablePersonsResult" class="mt-2 p-4 bg-gray-50 rounded-lg min-h-[100px]">
          <p class="text-gray-500 text-sm">点击查询按钮查看可再次开店的人员</p>
        </div>
      </div>
    </div>
    
    <!-- 表格区域 -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden">
      <div class="overflow-x-auto">
        <table id="shopTable" class="w-full table-shadow">
          <thead>
            <tr class="bg-gray-50 text-left">
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="index">
                序号 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="personName">
                人员信息 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="phoneNumber">
                手机号后四位 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="shopId">
                店铺编号 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="openDate">
                开店时间 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="depositAmount">
                押金金额 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="depositStatus">
                押金状态 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="depositDate">
                押金到账时间 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="closeType">
                退店类型 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="processDates">
                退店流程时间 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="shopStatus">
                店铺状态 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="phoneReusableDate">
                手机号可复用时间 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap sortable" data-sort="personReusableDate">
                人员可重开时间 <i class="fa fa-sort sort-icon"></i>
              </th>
              <th class="px-6 py-4 text-sm font-semibold text-gray-600 whitespace-nowrap">操作</th>
            </tr>
          </thead>
          <tbody id="tableBody">
            <!-- 表格内容将通过JavaScript动态生成 -->
          </tbody>
        </table>
      </div>
      
      <!-- 空状态 -->
      <div id="emptyState" class="py-20 text-center hidden">
        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
          <i class="fa fa-table text-gray-400 text-2xl"></i>
        </div>
        <h3 class="text-lg font-medium text-gray-900 mb-1">暂无记录</h3>
        <p class="text-gray-500 max-w-md mx-auto">点击"添加记录"按钮开始跟踪您的店铺信息</p>
        <button id="addFirstRowBtn" class="mt-4 bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg flex items-center mx-auto transition-custom shadow-md hover:shadow-lg">
          <i class="fa fa-plus mr-2"></i>添加第一条记录
        </button>
      </div>
    </div>
  </main>
  
  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 mt-12">
    <div class="container mx-auto px-4 py-6">
      <div class="text-center text-gray-500 text-sm">
        <p>© 2025 网店店铺管理系统 - 帮助您高效管理店铺资源</p>
      </div>
    </div>
  </footer>
  
  <!-- 添加/编辑记录模态框 -->
  <div id="recordModal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto m-4 shadow-xl transform transition-all">
      <div class="p-6 border-b border-gray-200">
        <div class="flex justify-between items-center">
          <h2 id="modalTitle" class="text-xl font-bold text-gray-800">添加店铺记录</h2>
          <button id="closeModal" class="text-gray-500 hover:text-gray-700 transition-custom">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
      </div>
      
      <form id="recordForm" class="p-6 space-y-5">
        <input type="hidden" id="recordId">
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
          <div>
            <label for="personName" class="block text-sm font-medium text-gray-700 mb-1">人员姓名/ID <span class="text-danger">*</span></label>
            <input type="text" id="personName" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
          </div>
          
          <div>
            <label for="phoneNumber" class="block text-sm font-medium text-gray-700 mb-1">手机号码后四位 <span class="text-danger">*</span></label>
            <input type="tel" id="phoneNumber" required pattern="\d{4}" placeholder="请输入后四位" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
          </div>
          
          <div>
            <label for="shopId" class="block text-sm font-medium text-gray-700 mb-1">店铺编号</label>
            <input type="text" id="shopId" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
          </div>
          
          <div>
            <label for="depositAmount" class="block text-sm font-medium text-gray-700 mb-1">押金金额（元） <span class="text-danger">*</span></label>
            <input type="number" id="depositAmount" required min="0" step="0.01" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
          </div>
          
          <div>
            <label for="openDate" class="block text-sm font-medium text-gray-700 mb-1">开店时间 <span class="text-danger">*</span></label>
            <input type="date" id="openDate" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
          </div>
          
          <div>
            <label for="closeType" class="block text-sm font-medium text-gray-700 mb-1">退店类型</label>
            <select id="closeType" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
              <option value="">未开始退店</option>
              <option value="有待付款">有待付款</option>
              <option value="无待付款">无待付款</option>
              <option value="有公示期">有公示期</option>
            </select>
          </div>
          
          <div>
            <label for="processStartDate" class="block text-sm font-medium text-gray-700 mb-1">退店流程开始时间</label>
            <input type="date" id="processStartDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
          </div>

          <div>
            <label for="depositStatus" class="block text-sm font-medium text-gray-700 mb-1">押金状态</label>
            <select id="depositStatus" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
              <option value="未到账">未到账</option>
              <option value="已到账">已到账</option>
            </select>
          </div>

          <div>
            <label for="depositDate" class="block text-sm font-medium text-gray-700 mb-1">押金到账时间</label>
            <input type="date" id="depositDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
          </div>
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">退店流程时间节点</label>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label for="closePromotionDate" class="block text-xs text-gray-500 mb-1">关闭推广时间</label>
              <input type="date" id="closePromotionDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
            </div>
            <div>
              <label for="refundApplyDate" class="block text-xs text-gray-500 mb-1">申请退款时间</label>
              <input type="date" id="refundApplyDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
            </div>
            <div>
              <label for="shopCloseDate" class="block text-xs text-gray-500 mb-1">店铺关闭时间</label>
              <input type="date" id="shopCloseDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
            </div>
          </div>
        </div>
        
        <div>
          <label for="shopStatus" class="block text-sm font-medium text-gray-700 mb-1">店铺状态 <span class="text-danger">*</span></label>
          <select id="shopStatus" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom">
            <option value="运营中">运营中</option>
            <option value="退店处理中">退店处理中</option>
            <option value="已关闭">已关闭</option>
          </select>
        </div>
        
        <div class="pt-2 flex justify-end space-x-3">
          <button type="button" id="cancelBtn" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-custom">取消</button>
          <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-custom shadow-sm hover:shadow">保存记录</button>
        </div>
      </form>
    </div>
  </div>
  
  <script>
    // 数据存储
    let shopRecords = JSON.parse(localStorage.getItem('shopRecords')) || [];
    let currentEditingId = null;
    let currentSort = {
      field: 'index',
      direction: 'asc' // 'asc' 或 'desc'
    };
    
    // DOM元素
    const tableBody = document.getElementById('tableBody');
    const emptyState = document.getElementById('emptyState');
    const recordModal = document.getElementById('recordModal');
    const recordForm = document.getElementById('recordForm');
    const modalTitle = document.getElementById('modalTitle');
    const closeModal = document.getElementById('closeModal');
    const cancelBtn = document.getElementById('cancelBtn');
    const addRowBtn = document.getElementById('addRowBtn');
    const addFirstRowBtn = document.getElementById('addFirstRowBtn');
    const exportXLSXBtn = document.getElementById('exportXLSX');
    const exportWPSBtn = document.getElementById('exportWPS');
    const filterPerson = document.getElementById('filterPerson');
    const filterPhone = document.getElementById('filterPhone');
    const filterStatus = document.getElementById('filterStatus');
    const filterCloseType = document.getElementById('filterCloseType');
    const filterDepositStatus = document.getElementById('filterDepositStatus');
    const resetFilter = document.getElementById('resetFilter');
    // 新增：可复用查询相关元素
    const checkReusablePhonesBtn = document.getElementById('checkReusablePhones');
    const checkReusablePersonsBtn = document.getElementById('checkReusablePersons');
    const reusablePhonesResult = document.getElementById('reusablePhonesResult');
    const reusablePersonsResult = document.getElementById('reusablePersonsResult');
    
    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
      // 为现有记录添加押金相关字段（数据迁移）
      migrateOldData();
      
      renderTable();
      updateStats();
      setupEventListeners();
      
      // 设置默认日期为今天
      const today = new Date().toISOString().split('T')[0];
      document.getElementById('openDate').value = today;
    });
    
    // 数据迁移：为旧记录添加押金相关字段
    function migrateOldData() {
      let needsMigration = false;
      
      shopRecords.forEach(record => {
        if (!record.hasOwnProperty('depositAmount')) {
          record.depositAmount = 0;
          record.depositStatus = '未到账';
          record.depositDate = '';
          needsMigration = true;
        }
      });
      
      if (needsMigration) {
        localStorage.setItem('shopRecords', JSON.stringify(shopRecords));
      }
    }
    
    // 设置事件监听器
    function setupEventListeners() {
      // 模态框控制
      addRowBtn.addEventListener('click', openAddModal);
      addFirstRowBtn.addEventListener('click', openAddModal);
      closeModal.addEventListener('click', closeModalFunc);
      cancelBtn.addEventListener('click', closeModalFunc);
      
      // 表单提交
      recordForm.addEventListener('submit', handleFormSubmit);
      
      // 筛选功能
      filterPerson.addEventListener('input', filterRecords);
      filterPhone.addEventListener('input', filterRecords);
      filterStatus.addEventListener('change', filterRecords);
      filterCloseType.addEventListener('change', filterRecords);
      filterDepositStatus.addEventListener('change', filterRecords);
      resetFilter.addEventListener('click', resetFilters);
      
      // 导出功能
      exportXLSXBtn.addEventListener('click', exportToXLSX);
      exportWPSBtn.addEventListener('click', exportToWPS);
      
      // 退店类型变更时自动计算日期
      document.getElementById('closeType').addEventListener('change', calculateProcessDates);
      document.getElementById('processStartDate').addEventListener('change', calculateProcessDates);
      
      // 押金状态变更时处理日期
      document.getElementById('depositStatus').addEventListener('change', function() {
        // 如果设置为已到账且未填写日期，则自动填充今天
        if (this.value === '已到账' && !document.getElementById('depositDate').value) {
          const today = new Date().toISOString().split('T')[0];
          document.getElementById('depositDate').value = today;
        }
      });
      
      // 排序功能
      document.querySelectorAll('.sortable').forEach(header => {
        header.addEventListener('click', () => {
          const field = header.getAttribute('data-sort');
          // 如果点击的是当前排序字段，则切换排序方向
          if (currentSort.field === field) {
            currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
          } else {
            // 否则，设置新的排序字段并默认升序
            currentSort.field = field;
            currentSort.direction = 'asc';
          }
          updateSortIcons();
          filterRecords(); // 重新筛选并排序
        });
      });
      
      // 新增：可复用查询事件
      checkReusablePhonesBtn.addEventListener('click', checkReusablePhones);
      checkReusablePersonsBtn.addEventListener('click', checkReusablePersons);
    }
    
    // 新增：查询可复用手机号
    function checkReusablePhones() {
      // 获取所有唯一的手机号尾号
      const allPhones = new Set(shopRecords.map(record => record.phoneNumber).filter(Boolean));
      
      if (allPhones.size === 0) {
        reusablePhonesResult.innerHTML = '<p class="text-gray-500">没有记录的手机号</p>';
        return;
      }
      
      const reusablePhones = [];
      
      // 检查每个手机号的所有使用记录是否都已到期
      allPhones.forEach(phone => {
        const recordsWithThisPhone = shopRecords.filter(record => record.phoneNumber === phone);
        let allExpired = true;
        
        recordsWithThisPhone.forEach(record => {
          // 检查该手机号在该记录中是否已到期
          if (!isDatePassed(record.phoneReusableDate)) {
            allExpired = false;
          }
        });
        
        if (allExpired) {
          reusablePhones.push(phone);
        }
      });
      
      if (reusablePhones.length === 0) {
        reusablePhonesResult.innerHTML = '<p class="text-gray-500">没有可复用的手机号尾号</p>';
      } else {
        reusablePhonesResult.innerHTML = `
          <p class="text-sm font-medium text-gray-700 mb-2">共 ${reusablePhones.length} 个可复用手机号尾号：</p>
          <div class="flex flex-wrap gap-2">
            ${reusablePhones.map(phone => `
              <span class="px-3 py-1 bg-success/10 text-success rounded-full text-sm">
                ${phone}
              </span>
            `).join('')}
          </div>
        `;
      }
    }
    
    // 新增：查询可复用人员
    function checkReusablePersons() {
      // 获取所有唯一的人员
      const allPersons = new Set(shopRecords.map(record => record.personName).filter(Boolean));
      
      if (allPersons.size === 0) {
        reusablePersonsResult.innerHTML = '<p class="text-gray-500">没有记录的人员</p>';
        return;
      }
      
      const reusablePersons = [];
      
      // 检查每个人员的所有店铺是否都已关闭且已过30天
      allPersons.forEach(person => {
        const recordsOfPerson = shopRecords.filter(record => record.personName === person);
        let canReuse = true;
        
        recordsOfPerson.forEach(record => {
          // 检查店铺是否已关闭且已过30天
          if (record.shopStatus !== '已关闭' || !isDatePassed(record.personReusableDate)) {
            canReuse = false;
          }
        });
        
        if (canReuse) {
          reusablePersons.push(person);
        }
      });
      
      if (reusablePersons.length === 0) {
        reusablePersonsResult.innerHTML = '<p class="text-gray-500">没有可再次开店的人员</p>';
      } else {
        reusablePersonsResult.innerHTML = `
          <p class="text-sm font-medium text-gray-700 mb-2">共 ${reusablePersons.length} 个可再次开店的人员：</p>
          <div class="flex flex-wrap gap-2">
            ${reusablePersons.map(person => `
              <span class="px-3 py-1 bg-success/10 text-success rounded-full text-sm">
                ${person}
              </span>
            `).join('')}
          </div>
        `;
      }
    }
    
    // 更新排序图标
    function updateSortIcons() {
      // 重置所有排序图标
      document.querySelectorAll('.sortable i').forEach(icon => {
        icon.className = 'fa fa-sort sort-icon';
      });
      
      // 设置当前排序字段的图标
      const currentHeader = document.querySelector(`.sortable[data-sort="${currentSort.field}"] i`);
      if (currentHeader) {
        currentHeader.className = currentSort.direction === 'asc' 
          ? 'fa fa-sort-asc sort-icon' 
          : 'fa fa-sort-desc sort-icon';
      }
    }
    
    // 对记录进行排序
    function sortRecords(records) {
      return [...records].sort((a, b) => {
        let valueA, valueB;
        
        // 根据不同的排序字段获取对应的值
        switch(currentSort.field) {
          case 'index':
            // 序号排序 - 找到原始数组中的位置
            const indexA = shopRecords.findIndex(record => record.id === a.id);
            const indexB = shopRecords.findIndex(record => record.id === b.id);
            return currentSort.direction === 'asc' ? indexA - indexB : indexB - indexA;
          case 'personName':
            valueA = a.personName || '';
            valueB = b.personName || '';
            break;
          case 'phoneNumber':
            valueA = a.phoneNumber || '';
            valueB = b.phoneNumber || '';
            break;
          case 'shopId':
            valueA = a.shopId || '';
            valueB = b.shopId || '';
            break;
          case 'openDate':
            valueA = a.openDate || '';
            valueB = b.openDate || '';
            break;
          case 'depositAmount':
            valueA = parseFloat(a.depositAmount) || 0;
            valueB = parseFloat(b.depositAmount) || 0;
            break;
          case 'depositStatus':
            // 为状态定义排序优先级
            const depositOrder = { '未到账': 1, '已到账': 2 };
            valueA = depositOrder[a.depositStatus] || 0;
            valueB = depositOrder[b.depositStatus] || 0;
            break;
          case 'depositDate':
            valueA = a.depositDate || '';
            valueB = b.depositDate || '';
            break;
          case 'closeType':
            valueA = a.closeType || '';
            valueB = b.closeType || '';
            break;
          case 'processDates':
            // 使用店铺关闭时间作为排序依据
            valueA = a.shopCloseDate || '';
            valueB = b.shopCloseDate || '';
            break;
          case 'shopStatus':
            // 为状态定义排序优先级
            const statusOrder = { '运营中': 1, '退店处理中': 2, '已关闭': 3 };
            valueA = statusOrder[a.shopStatus] || 0;
            valueB = statusOrder[b.shopStatus] || 0;
            break;
          case 'phoneReusableDate':
            valueA = a.phoneReusableDate || '';
            valueB = b.phoneReusableDate || '';
            break;
          case 'personReusableDate':
            valueA = a.personReusableDate || '';
            valueB = b.personReusableDate || '';
            break;
          default:
            return 0;
        }
        
        // 字符串比较
        if (typeof valueA === 'string' && typeof valueB === 'string') {
          const comparison = valueA.localeCompare(valueB, 'zh-CN');
          return currentSort.direction === 'asc' ? comparison : -comparison;
        }
        
        // 数字比较
        return currentSort.direction === 'asc' ? valueA - valueB : valueB - valueA;
      });
    }
    
    // 打开添加记录模态框
    function openAddModal() {
      currentEditingId = null;
      modalTitle.textContent = '添加店铺记录';
      recordForm.reset();
      
      // 设置默认值
      const today = new Date().toISOString().split('T')[0];
      document.getElementById('openDate').value = today;
      document.getElementById('depositStatus').value = '未到账';
      
      recordModal.classList.remove('hidden');
      document.getElementById('personName').focus();
    }
    
    // 打开编辑记录模态框
    function openEditModal(id) {
      const record = shopRecords.find(r => r.id === id);
      if (!record) return;
      
      currentEditingId = id;
      modalTitle.textContent = '编辑店铺记录';
      
      // 填充表单数据
      document.getElementById('recordId').value = record.id;
      document.getElementById('personName').value = record.personName || '';
      document.getElementById('phoneNumber').value = record.phoneNumber || '';
      document.getElementById('shopId').value = record.shopId || '';
      document.getElementById('depositAmount').value = record.depositAmount || 0;
      document.getElementById('openDate').value = record.openDate || '';
      document.getElementById('closeType').value = record.closeType || '';
      document.getElementById('processStartDate').value = record.processStartDate || '';
      document.getElementById('closePromotionDate').value = record.closePromotionDate || '';
      document.getElementById('refundApplyDate').value = record.refundApplyDate || '';
      document.getElementById('shopCloseDate').value = record.shopCloseDate || '';
      document.getElementById('shopStatus').value = record.shopStatus || '运营中';
      document.getElementById('depositStatus').value = record.depositStatus || '未到账';
      document.getElementById('depositDate').value = record.depositDate || '';
      
      recordModal.classList.remove('hidden');
    }
    
    // 关闭模态框
    function closeModalFunc() {
      recordModal.classList.add('hidden');
    }
    
    // 处理表单提交
    function handleFormSubmit(e) {
      e.preventDefault();
      
      const formData = {
        id: currentEditingId || Date.now().toString(),
        personName: document.getElementById('personName').value,
        phoneNumber: document.getElementById('phoneNumber').value,
        shopId: document.getElementById('shopId').value,
        depositAmount: document.getElementById('depositAmount').value,
        openDate: document.getElementById('openDate').value,
        closeType: document.getElementById('closeType').value,
        processStartDate: document.getElementById('processStartDate').value,
        closePromotionDate: document.getElementById('closePromotionDate').value,
        refundApplyDate: document.getElementById('refundApplyDate').value,
        shopCloseDate: document.getElementById('shopCloseDate').value,
        shopStatus: document.getElementById('shopStatus').value,
        depositStatus: document.getElementById('depositStatus').value,
        depositDate: document.getElementById('depositDate').value,
        phoneReusableDate: calculatePhoneReusableDate(document.getElementById('shopCloseDate').value),
        personReusableDate: calculatePersonReusableDate(document.getElementById('shopCloseDate').value)
      };
      
      if (currentEditingId) {
        // 更新现有记录
        const index = shopRecords.findIndex(r => r.id === currentEditingId);
        if (index !== -1) {
          shopRecords[index] = formData;
        }
      } else {
        // 添加新记录
        shopRecords.unshift(formData);
      }
      
      // 保存到本地存储
      localStorage.setItem('shopRecords', JSON.stringify(shopRecords));
      
      // 刷新表格
      renderTable();
      updateStats();
      
      // 关闭模态框
      closeModalFunc();
    }
    
    // 根据退店类型和开始时间计算流程日期
    function calculateProcessDates() {
      const closeType = document.getElementById('closeType').value;
      const processStartDate = document.getElementById('processStartDate').value;
      
      if (!closeType || !processStartDate) return;
      
      const start = new Date(processStartDate);
      let closePromotion, refundApply, shopClose;
      
      switch(closeType) {
        case '有待付款':
          // 有待付款：等待48小时 → 关闭推广 → 2天后申请退款 → 15天后关闭店铺
          closePromotion = new Date(start);
          closePromotion.setDate(start.getDate() + 2); // 48小时后
          
          refundApply = new Date(closePromotion);
          refundApply.setDate(closePromotion.getDate() + 2);
          
          shopClose = new Date(refundApply);
          shopClose.setDate(refundApply.getDate() + 15);
          break;
          
        case '无待付款':
          // 无待付款：直接关闭推广 → 2天后申请退款 → 15天后关闭店铺
          closePromotion = new Date(start); // 立即关闭推广
          
          refundApply = new Date(closePromotion);
          refundApply.setDate(closePromotion.getDate() + 2);
          
          shopClose = new Date(refundApply);
          shopClose.setDate(refundApply.getDate() + 15);
          break;
          
        case '有公示期':
          // 有公示期：开启公示期 → 30天后申请退款 → 15天后关闭店铺
          closePromotion = null; // 无关闭推广步骤
          
          refundApply = new Date(start);
          refundApply.setDate(start.getDate() + 30);
          
          shopClose = new Date(refundApply);
          shopClose.setDate(refundApply.getDate() + 15);
          break;
      }
      
      // 设置日期输入框的值
      if (closePromotion) {
        document.getElementById('closePromotionDate').value = closePromotion.toISOString().split('T')[0];
      } else {
        document.getElementById('closePromotionDate').value = '';
      }
      
      if (refundApply) {
        document.getElementById('refundApplyDate').value = refundApply.toISOString().split('T')[0];
      }
      
      if (shopClose) {
        document.getElementById('shopCloseDate').value = shopClose.toISOString().split('T')[0];
      }
    }
    
    // 计算手机号可复用日期（店铺关闭次日）
    function calculatePhoneReusableDate(shopCloseDate) {
      if (!shopCloseDate) return '';
      
      const closeDate = new Date(shopCloseDate);
      closeDate.setDate(closeDate.getDate() + 1);
      return closeDate.toISOString().split('T')[0];
    }
    
    // 计算人员可重开日期（店铺关闭后30天）
    function calculatePersonReusableDate(shopCloseDate) {
      if (!shopCloseDate) return '';
      
      const closeDate = new Date(shopCloseDate);
      closeDate.setDate(closeDate.getDate() + 30);
      return closeDate.toISOString().split('T')[0];
    }
    
    // 渲染表格
    function renderTable(filteredRecords = null) {
      let records = filteredRecords || shopRecords;
      // 应用排序
      records = sortRecords(records);
      
      if (records.length === 0) {
        tableBody.innerHTML = '';
        emptyState.classList.remove('hidden');
        return;
      }
      
      emptyState.classList.add('hidden');
      tableBody.innerHTML = '';
      
      records.forEach((record, index) => {
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-200 hover:bg-gray-50 transition-custom';
        
        // 状态标签样式
        let statusClass = '';
        switch(record.shopStatus) {
          case '运营中':
            statusClass = 'bg-success/10 text-success';
            break;
          case '退店处理中':
            statusClass = 'bg-warning/10 text-warning';
            break;
          case '已关闭':
            statusClass = 'bg-gray-100 text-gray-600';
            break;
        }
        
        // 押金状态样式
        let depositClass = '';
        switch(record.depositStatus) {
          case '已到账':
            depositClass = 'bg-success/10 text-success';
            break;
          case '未到账':
            depositClass = 'bg-warning/10 text-warning';
            break;
        }
        
        // 构建流程时间显示
        let processDatesHtml = '';
        if (record.closeType) {
          const dates = [];
          if (record.closePromotionDate) dates.push(`关推: ${formatDate(record.closePromotionDate)}`);
          if (record.refundApplyDate) dates.push(`申请退款: ${formatDate(record.refundApplyDate)}`);
          if (record.shopCloseDate) dates.push(`关闭: ${formatDate(record.shopCloseDate)}`);
          processDatesHtml = dates.join('<br>');
        }
        
        row.innerHTML = `
          <td class="px-6 py-4 text-sm text-gray-600 whitespace-nowrap">${index + 1}</td>
          <td class="px-6 py-4 text-sm text-gray-800 whitespace-nowrap">${record.personName || '-'}</td>
          <td class="px-6 py-4 text-sm text-gray-800 whitespace-nowrap">${record.phoneNumber || '-'}</td>
          <td class="px-6 py-4 text-sm text-gray-800 whitespace-nowrap">${record.shopId || '-'}</td>
          <td class="px-6 py-4 text-sm text-gray-600 whitespace-nowrap">${formatDate(record.openDate)}</td>
          <td class="px-6 py-4 text-sm text-gray-600 whitespace-nowrap">${record.depositAmount ? '¥' + parseFloat(record.depositAmount).toFixed(2) : '-'}</td>
          <td class="px-6 py-4 whitespace-nowrap">
            <span class="status-badge ${depositClass}">${record.depositStatus || '-'}</span>
          </td>
          <td class="px-6 py-4 text-sm text-gray-600 whitespace-nowrap">${formatDate(record.depositDate)}</td>
          <td class="px-6 py-4 text-sm text-gray-600 whitespace-nowrap">${record.closeType || '-'}</td>
          <td class="px-6 py-4 text-sm text-gray-600 whitespace-nowrap">${processDatesHtml || '-'}</td>
          <td class="px-6 py-4 whitespace-nowrap">
            <span class="status-badge ${statusClass}">${record.shopStatus}</span>
          </td>
          <td class="px-6 py-4 text-sm ${isDatePassed(record.phoneReusableDate) ? 'text-success' : 'text-gray-600'} whitespace-nowrap">
            ${formatDate(record.phoneReusableDate) || '-'}
            ${isDatePassed(record.phoneReusableDate) ? '<i class="fa fa-check-circle ml-1"></i>' : ''}
          </td>
          <td class="px-6 py-4 text-sm ${isDatePassed(record.personReusableDate) ? 'text-success' : 'text-gray-600'} whitespace-nowrap">
            ${formatDate(record.personReusableDate) || '-'}
            ${isDatePassed(record.personReusableDate) ? '<i class="fa fa-check-circle ml-1"></i>' : ''}
          </td>
          <td class="px-6 py-4 whitespace-nowrap">
            <div class="flex space-x-2">
              <button class="text-primary hover:text-primary/80 transition-custom edit-btn" data-id="${record.id}">
                <i class="fa fa-pencil"></i>
              </button>
              <button class="text-danger hover:text-danger/80 transition-custom delete-btn" data-id="${record.id}">
                <i class="fa fa-trash"></i>
              </button>
            </div>
          </td>
        `;
        
        tableBody.appendChild(row);
      });
      
      // 添加编辑和删除按钮事件
      document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', () => openEditModal(btn.dataset.id));
      });
      
      document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', () => deleteRecord(btn.dataset.id));
      });
    }
    
    // 格式化日期显示
    function formatDate(dateString) {
      if (!dateString) return '-';
      
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
    
    // 检查日期是否已过
    function isDatePassed(dateString) {
      if (!dateString) return false;
      
      const date = new Date(dateString);
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      return date <= today;
    }
    
    // 删除记录
    function deleteRecord(id) {
      if (confirm('确定要删除这条记录吗？此操作不可撤销。')) {
        shopRecords = shopRecords.filter(record => record.id !== id);
        localStorage.setItem('shopRecords', JSON.stringify(shopRecords));
        renderTable();
        updateStats();
      }
    }
    
    // 筛选记录
    function filterRecords() {
      const person = filterPerson.value.toLowerCase();
      const phone = filterPhone.value.toLowerCase();
      const status = filterStatus.value;
      const closeType = filterCloseType.value;
      const depositStatus = filterDepositStatus.value;
      
      const filtered = shopRecords.filter(record => {
        const matchesPerson = !person || (record.personName && record.personName.toLowerCase().includes(person));
        const matchesPhone = !phone || (record.phoneNumber && record.phoneNumber.toLowerCase().includes(phone));
        const matchesStatus = !status || record.shopStatus === status;
        const matchesCloseType = !closeType || record.closeType === closeType;
        const matchesDepositStatus = !depositStatus || record.depositStatus === depositStatus;
        
        return matchesPerson && matchesPhone && matchesStatus && matchesCloseType && matchesDepositStatus;
      });
      
      renderTable(filtered);
    }
    
    // 重置筛选条件
    function resetFilters() {
      filterPerson.value = '';
      filterPhone.value = '';
      filterStatus.value = '';
      filterCloseType.value = '';
      filterDepositStatus.value = '';
      renderTable();
    }
    
    // 更新统计数据
    function updateStats() {
      // 总店铺数
      document.getElementById('totalShops').textContent = shopRecords.length;
      
      // 在用手机号（状态为运营中或退店处理中的手机号）
      const usedPhones = new Set();
      shopRecords.forEach(record => {
        if (record.phoneNumber && ['运营中', '退店处理中'].includes(record.shopStatus)) {
          usedPhones.add(record.phoneNumber);
        }
      });
      document.getElementById('usedPhones').textContent = usedPhones.size;
      
      // 待处理退店（状态为退店处理中的记录）
      const pendingClose = shopRecords.filter(record => record.shopStatus === '退店处理中').length;
      document.getElementById('pendingClose').textContent = pendingClose;
      
      // 可复用资源（手机号可复用 + 人员可重开）
      let reusable = 0;
      shopRecords.forEach(record => {
        if (isDatePassed(record.phoneReusableDate)) reusable++;
        if (isDatePassed(record.personReusableDate)) reusable++;
      });
      document.getElementById('reusableResources').textContent = reusable;
    }
    
    // 导出为XLSX
    function exportToXLSX() {
      if (shopRecords.length === 0) {
        alert('没有可导出的数据');
        return;
      }
      
      // 准备导出数据
      const exportData = shopRecords.map((record, index) => ({
        '序号': index + 1,
        '人员信息': record.personName || '',
        '手机号后四位': record.phoneNumber || '',
        '店铺编号': record.shopId || '',
        '押金金额(元)': record.depositAmount || 0,
        '押金状态': record.depositStatus || '',
        '押金到账时间': formatDate(record.depositDate),
        '开店时间': formatDate(record.openDate),
        '退店类型': record.closeType || '',
        '退店流程开始时间': formatDate(record.processStartDate),
        '关闭推广时间': formatDate(record.closePromotionDate),
        '申请退款时间': formatDate(record.refundApplyDate),
        '店铺关闭时间': formatDate(record.shopCloseDate),
        '店铺状态': record.shopStatus || '',
        '手机号可复用时间': formatDate(record.phoneReusableDate),
        '人员可重开时间': formatDate(record.personReusableDate)
      }));
      
      // 创建工作簿和工作表
      const ws = XLSX.utils.json_to_sheet(exportData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '店铺记录');
      
      // 导出文件
      XLSX.writeFile(wb, `网店店铺记录_${new Date().toLocaleDateString()}.xlsx`);
    }
    
    // 导出为WPS（实际上与XLSX格式相同，WPS可以打开）
    function exportToWPS() {
      if (shopRecords.length === 0) {
        alert('没有可导出的数据');
        return;
      }
      
      // 准备导出数据
      const exportData = shopRecords.map((record, index) => ({
        '序号': index + 1,
        '人员信息': record.personName || '',
        '手机号后四位': record.phoneNumber || '',
        '店铺编号': record.shopId || '',
        '押金金额(元)': record.depositAmount || 0,
        '押金状态': record.depositStatus || '',
        '押金到账时间': formatDate(record.depositDate),
        '开店时间': formatDate(record.openDate),
        '退店类型': record.closeType || '',
        '退店流程开始时间': formatDate(record.processStartDate),
        '关闭推广时间': formatDate(record.closePromotionDate),
        '申请退款时间': formatDate(record.refundApplyDate),
        '店铺关闭时间': formatDate(record.shopCloseDate),
        '店铺状态': record.shopStatus || '',
        '手机号可复用时间': formatDate(record.phoneReusableDate),
        '人员可重开时间': formatDate(record.personReusableDate)
      }));
      
      // 创建工作簿和工作表
      const ws = XLSX.utils.json_to_sheet(exportData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '店铺记录');
      
      // 导出文件（WPS支持XLSX格式）
      XLSX.writeFile(wb, `网店店铺记录_${new Date().toLocaleDateString()}.xls`);
    }
  </script>
</body>
</html>
